#pragma once

#include "LuaCommon.h"

namespace LuaGui {
#if defined(USE_LIBUV)

#include "uv.h"

	class TcpServer {
	public:
		TcpServer();
		~TcpServer();

		static TcpServer* GetTcpServerByUID(uint64_t uid);
		unsigned long long GetUID() { return (unsigned long long)this; }
		int Start(std::string ip = "0.0.0.0", unsigned int port = 0);
		void Stop();
	private:
		uv_tcp_t m_uv_tcp;

		static std::unordered_map<uint64_t, TcpServer*> s_tcp_servers;
	};

	class TcpSocket {
	public:
		TcpSocket();
		~TcpSocket();
		static TcpSocket* GetTcpServerByUID(uint64_t uid);

		int Send(std::string buf);
		void Close();
		unsigned long long GetUID() { return (unsigned long long)this; }
		unsigned long long GetServerUID() { return m_server_uid; }
		void SetServerUID(unsigned long long uid) { m_server_uid = uid; }
		std::string GetIp();
		unsigned int GetPort();
		std::string GetPeerIp();
		unsigned int GetPeerPort();

	public:
		uv_stream_t* GetUVStream() { return (uv_stream_t*)&m_uv_tcp; }
		uv_tcp_t* GetUVTcp() { return &m_uv_tcp; }
	private:
		uv_tcp_t m_uv_tcp;
		unsigned long long m_server_uid;
		static std::unordered_map<uint64_t, TcpSocket*> s_tcp_sockets;
	};

	class LuaNet {
	public:
		static void Register(lua_State* L);

		static TcpServer* StartServer(std::string ip = "0.0.0.0", unsigned int port = 80);
		static void StopServer(TcpServer* server);
		static TcpSocket* ConnectServer(std::string ip = "0.0.0.0", unsigned int port = 80);
	};

#else
	class LuaNet
	{
	public:
		static void Register(lua_State* L) {}
	};
#endif	
}


